import React, { useEffect, useState,useRef } from 'react'
import { Table, Button, Modal, Switch, Form, Input, Select } from 'antd'
import axios from 'axios'
import { OrderedListOutlined, DeleteOutlined } from '@ant-design/icons';
import UserForm from '../../../components/user-manage/userForm'  // form 表单
function UserList() {
    const [dataSource, setdataSource] = useState([])
    const [isAddvisible, setisAddvisible] = useState(false)
    const [roleList, setroleList] = useState([])
    const [regionList, setregionList] = useState([])
    const addForm = useRef(null)
    const updataForm = useRef({})
    const [form] = Form.useForm();
    const { Option } = Select;
    const [isUpdatavisible,setisUpdatavisible]=useState(false) // 更新form表单
    const [isUpdataDisable,setisUpdataDisable]=useState(false)
    const [current,setcurrent] = useState(null)
    const columns = [
        {
            title: '区域',
            dataIndex: "region",
            filters: [
                ...regionList.map(item=>({
                    text:item.title,
                    value:item.value
                })),
                {
                    text:"全球",
                    value:""
                }
              ],
            onFilter:(value,item)=>item.region===value,
            render(region) {
                return <b>{region ? region : '全球'}</b>
            }
        },
        {
            title: '角色名称',
            dataIndex: "role",
            render(role) {
                return role?.roleName
            }
        },

        {
            title: '用户名',
            dataIndex: "username"
        },
        {
            title: '用户状态',
            dataIndex: "roleState",
            render(roleState, item) {
                return <div>
                    <Switch disabled={item.default} checked={roleState} 
                    onChange={()=>handleChange(item)}
                    ></Switch>
                </div>
            }
        },
        {
            title: '操作',
            dataIndex: "",
            render(item) {
                return <div>
                    <Button disabled={item.default} type="danger" shape="circle" icon={<DeleteOutlined />} onClick={() => deleteConfirm(item)} />
                    <Button disabled={item.default} type="primary" shape="circle" icon={<OrderedListOutlined />} onClick={() => handleUpdata(item)} />

                </div>
            }
        },
    ]
    const {roleId,region,username} =JSON.parse(localStorage.getItem("token"))
    // 修改状态
    const handleChange=(e)=>{
        console.log(e);
        e.roleState=!e.roleState
        setdataSource([...dataSource])
        axios.patch("/users/"+e.id,{
            roleState:e.roleState
        })
    }
    //删除确认框
    var deleteConfirm = (item) => {
        console.log(item);
        Modal.confirm({
            title: 'Confirm',
            icon: <DeleteOutlined />,
            content: '确定删除角色？',
            onOk() {
                deleteMethod(item)
            },
            onCancel() {
                console.log('Cancel');
            },
        });
    }
    // 执行删除方法
    var deleteMethod = (item) => {
        setdataSource(dataSource.filter(data => data.id !== item.id))
        axios.delete(`/users/${item.id}`)
    }
    // 点击更新按钮
    const handleUpdata = (item) => {
        setTimeout(() => {
            setisUpdatavisible(true)
            setcurrent(item)
            if (item.roleId===1){
                setisUpdataDisable(true)
            }else{
                setisUpdataDisable(false)
            }
            updataForm.current.setFieldsValue(item)
        }, 1);
    };
    // 获取roles,region列表
    const getroleList = async () => {
        var roles = await axios.get('/roles')
        var region = await axios.get('/regions')
        setroleList(roles.data)
        setregionList(region.data)
    }
    // 获取表格数据
    const roleObj={
        '1':"superadmin",
        '2':"admin" ,
        '3':"editor"
    }
    const getDataList = async () => {
        var res = await axios.get('/users?_expand=role')
        const list = res.data
        setdataSource(roleObj[roleId]==='superadmin'?list:[
            ...list.filter(item=>item.username===username),
            ...list.filter(item=>item.region===region && roleObj[item.roleId]==='editor')
        ])
    }
    // 添加数据
    const addFormOk=()=>{
        addForm.current.validateFields().then(value=>{
            setisAddvisible(false)
            addForm.current.resetFields()
            axios.post("/users",{
                ...value,
                "roleState":true,
                "default":false
            }).then(res=>{
                console.log(res.data);
                setdataSource([...dataSource,
                    {
                        
                        ...res.data,
                        role:roleList.filter(item=>item.id===value.roleId)[0]

                    }
                ])
                getDataList()
            })
        })
    }
    // 更新form OK
    const updataFormOk=()=>{
        updataForm.current.validateFields().then(value=>{
            updataForm.current.resetFields()
            setdataSource(dataSource.map(item=>{
                if (item.id===current.id){
                    return {
                        ...item,
                        ...value,
                        role:roleList.filter(data=>data.id===value.roleId)[0]
                    }
                }
                return item
            }))
            // axios.patch("/users/"+value.id)
            setisUpdatavisible(false)
            axios.patch("/users/"+current.id,value)
            
        })

    
    }
    useEffect(() => {
        getDataList()
        getroleList()
    }, [])
    return (
        <div>
            <Button type='primary' onClick={() => { setisAddvisible(true) }}>添加用户</Button>
            <Table dataSource={dataSource} columns={columns}
                rowKey={(item) => item.id}
                pagination={{
                    pageSize: 5
                }} />
            <Modal
                visible={isAddvisible}
                title="添加用户"
                okText="确认"
                cancelText="取消"
                onCancel={() => { setisAddvisible(false)  }}
                onOk={() => addFormOk()}
            >
                <UserForm regionList={regionList} roleList={roleList} ref={addForm}/>
            </Modal>
            <Modal
                visible={isUpdatavisible}
                title="更新用户"
                okText="更新"
                cancelText="取消"
                onCancel={() => { setisUpdatavisible(false) 
                    setisUpdataDisable(!isUpdataDisable)
                }}
                onOk={() => updataFormOk()}
            >
                <UserForm 
                regionList={regionList} 
                roleList={roleList} 
                isUpdataDisable={isUpdataDisable}
                isUpdate={true}
                ref={updataForm}/>
            </Modal>
        </div>
    )
}

export default UserList

